package com.example.communist_app_api.service.impl;

<<<<<<< HEAD
import cn.hutool.core.lang.func.Func1;
import com.example.communist_app_api.db.dao.OrganizationDao;
import com.example.communist_app_api.db.dao.PhotoDao;
import com.example.communist_app_api.db.dao.UserDao;

import com.example.communist_app_api.db.dto.PhotoDTO;
import com.example.communist_app_api.db.dto.PhotoUserDTO;
import com.example.communist_app_api.db.dto.PhotoUserDetailDTO;
import com.example.communist_app_api.db.dto.UserOrganizationDTO;
import com.example.communist_app_api.db.pojo.Organization;
import com.example.communist_app_api.db.pojo.Photo;
import com.example.communist_app_api.db.pojo.User;
import com.example.communist_app_api.db.pojo.UserOrganization;
<<<<<<< HEAD
import com.example.communist_app_api.enums.SenderNameEnum;
=======
import com.example.communist_app_api.db.dao.OrganizationDao;
import com.example.communist_app_api.db.dao.PhotoDao;
import com.example.communist_app_api.db.dao.UserDao;
import com.example.communist_app_api.db.dto.PhotoUserDTO;
import com.example.communist_app_api.db.dto.PhotoUserDetailDTO;
import com.example.communist_app_api.db.dto.UserOrganizationDTO;
import com.example.communist_app_api.db.pojoDto.Organization;
import com.example.communist_app_api.db.pojoDto.Photo;
import com.example.communist_app_api.db.pojoDto.User;
>>>>>>> 党建uniapp/dev
=======
>>>>>>> parent of aec1d46 (消息模块的搭建和配合其他模块消息的发送和收取)
import com.example.communist_app_api.service.PhotoService;
import com.example.communist_app_api.service.UserOrganizationService;
import com.example.communist_app_api.util.StringUtil;
import com.example.communist_app_api.vo.uniapp.req.PhotoShowReq;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class PhotoServiceImpl implements PhotoService {

    @Autowired
    PhotoDao photoDao;

    @Autowired
    UserDao userDao;

    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    private OrganizationDao organizationDao;


    @Override
    public Integer createPhoto(String content, Integer userId, List<String> photoUrlList,String title) {
        Photo photo=new Photo();
        photo.setContent(content);
        photo.setUserId(userId);
        photo.setAuditorId(0);
        //list转String字符存储
        String photoUrl = photoUrlList.stream().collect(Collectors.joining(","));
        //String转List
        // List<String> uids= Arrays.asList(photoUrl.split(","));
        photo.setImageUrl(photoUrl);
        photo.setTitle(title);
        return photoDao.insert(photo);
    }

    @Override
    public Photo selectPhoto(Integer photoId) {
        return  photoDao.selectByPrimaryKey(photoId);
    }

    @Override
    public PhotoUserDetailDTO selectPhotoByPhotoId(Integer photoId) {
        Photo photo = photoDao.selectByPrimaryKey(photoId);
        User user = userDao.getUserByUserId(photo.getUserId());
        PhotoUserDetailDTO userDetailDTO = photoToPhotoUserDetailDTO(photo, user);
        String nameDesensitization = StringUtil.nameDesensitization(user.getName());
        //暂时不需要脱敏
        //userDetailDTO.setUserName(nameDesensitization);
        userDetailDTO.setUserName(user.getName());
        userDetailDTO.setOrganizationName(userOrganizationService.getOrganizationByUserId(user.getId()).getOrganizationName());
        return userDetailDTO;
    }

    /**
     *
     * @param photoShowReq 图片显示参数
     * @param userId    当前登录uniApp的用户Id
     * @return
     */
    @Override
    public  List<PhotoUserDTO> selectAllPhoto(PhotoShowReq photoShowReq,Integer userId) {
        //信息不互通，党支部，总支
        //根据userId去查询OrganizationId
        Organization organization = userOrganizationService.getOrganizationByUserId(userId);
        //判断当前组织层级是哪一个层级
        Integer grandParentId = organizationDao.getOrganizationByOrganizationId(organization.getParentId()).getParentId();
        //创建photoList List<Photo> photoList
        List<PhotoDTO> photoList = new ArrayList<>();
        List<Integer> organizationIdList = new ArrayList<>();
        organizationIdList.add(organization.getId());
        if (grandParentId == 0){
            //说明该层级是党总支部,获取总支和下面支部的所有随手拍照片
            organizationIdList.addAll(organizationDao.getOrganizationIdListByParentId(organization.getId()));
        }else {
            //说明该层级是党支部，获取党总支发布的随手拍和本支部发布的随手拍
            //添加总支到organizationIdList中
            organizationIdList.add(organizationDao.getOrganizationByOrganizationId(organization.getParentId()).getId());
        }
        photoList = photoDao.selectAllPhoto(photoShowReq.getContent(),photoShowReq.getTitle(),organizationIdList);
        List<PhotoUserDTO> photoUserDTOList=new ArrayList<>();
        if(photoList.size()==0){
          return photoUserDTOList;
        }
        //userIdList去重
        List<Integer> userIdList = photoList.stream().map(PhotoDTO::getUserId).distinct().collect(Collectors.toList());
        List<User> userList = userDao.getUserListByIds(userIdList);
        List<UserOrganizationDTO> userOrganizationList = userOrganizationService.getUserOrganizationListByUserIdList(userIdList);
        Integer skip= (photoShowReq.getPageNum()-1)*photoShowReq.getPageSize();
        Map<Integer, User> userMap = userList.stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        Map<Integer, String> organizationNameMap = userOrganizationList.stream()
                .collect(Collectors.toMap(UserOrganizationDTO::getUserId, UserOrganizationDTO::getOrganizationName));
        photoUserDTOList = photoList.stream().map(photo -> {
            User user = userMap.get(photo.getUserId());
            PhotoUserDTO photoUserDTO = new PhotoUserDTO();
            String nameDesensitization = StringUtil.nameDesensitization(user.getName());
            photoUserDTO.setId(photo.getId());
            //暂时不需要脱敏
            //photoUserDTO.setUserName(nameDesensitization);
            photoUserDTO.setUserName(user.getName());
            photoUserDTO.setOrganizationName(organizationNameMap.get(photo.getUserId()));
            photoUserDTO.setAvatar(user.getPhoto());
            photoUserDTO.setUserId(user.getId());
            photoUserDTO.setTitle(photo.getTitle());
            photoUserDTO.setCreatedTime(photo.getCreatedTime());
            String imageUrl = photo.getImageUrl();
            String photoUrl = imageUrl.split(",")[0];
            photoUserDTO.setPhotoUrl(photoUrl);
            return photoUserDTO;
        }).skip(skip)
                    .limit(photoShowReq.getPageSize())
                    .collect(Collectors.toList());


        return photoUserDTOList;
    }

    @Override
    public List<PhotoUserDetailDTO> selectPhotoByUserId(PhotoShowReq photoShowReq,Integer userId) {
        Integer skip= (photoShowReq.getPageNum()-1)*photoShowReq.getPageSize();
        List<Photo> photoList = photoDao.selectByUserId(userId);
        List<PhotoUserDetailDTO> dtoList = photoList.stream().map(photo -> {
            PhotoUserDetailDTO userDetailDTO = new PhotoUserDetailDTO();
            userDetailDTO.setId(photo.getId());
            userDetailDTO.setTitle(photo.getTitle());
            userDetailDTO.setContent(photo.getContent());
            String imageUrl = photo.getImageUrl();
            String[] split = imageUrl.split(",");
            userDetailDTO.setPhotoUrlList(Arrays.asList(split));
            userDetailDTO.setCreatedTime(photo.getCreatedTime());
            return userDetailDTO;
        })
                .skip(skip)
                .limit(photoShowReq.getPageSize())
                .collect(Collectors.toList());

        return dtoList;
    }

    @Override
    public Integer deletePhotoByPhotoId(Integer photoId) {
        return photoDao.deleteByPrimaryKey(photoId);
    }

    @Override
    public PageInfo<PhotoUserDetailDTO> selectAllPhotoByAudit( Integer organizationId, PhotoShowReq req) {
        Page<PhotoUserDetailDTO> page=new Page<>(req.getPageNum(),req.getPageSize());
        Integer skip= (req.getPageNum()-1)*req.getPageSize();
        List<Photo> list = photoDao.selectAllPhotoByAudit(organizationId,req.getTitle(),req.getContent());
        List<PhotoUserDetailDTO> photoUserDTOList=new ArrayList<>();
        if(list.size()==0){
            page.addAll(photoUserDTOList);
            PageInfo<PhotoUserDetailDTO> pageInfo=new PageInfo<>(page);
            return pageInfo;
        }
        List<Integer> userIdList = list.stream().map(Photo::getUserId).collect(Collectors.toList());
        List<User> users = userDao.getUserListByIds(userIdList);
        Map<Integer, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));
        photoUserDTOList = list.stream().map(photo -> {
                    User user = userMap.get(photo.getUserId());
                    return photoToPhotoUserDetailDTO(photo, user);
                })
                .collect(Collectors.toList());
        page.setTotal(photoUserDTOList.size());
        photoUserDTOList = photoUserDTOList.stream().skip(skip)
                .limit(req.getPageSize()).collect(Collectors.toList());
        page.addAll(photoUserDTOList);
        return new PageInfo<>(page);
    }

    private PhotoUserDetailDTO photoToPhotoUserDetailDTO(Photo photo,User user){
        PhotoUserDetailDTO userDetailDTO=new PhotoUserDetailDTO();
        userDetailDTO.setAvatar(user.getPhoto());
        userDetailDTO.setId(photo.getId());
        userDetailDTO.setUserName(user.getName());
        userDetailDTO.setAvatar(user.getPhoto());
        userDetailDTO.setUserId(user.getId());
        userDetailDTO.setTitle(photo.getTitle());
        userDetailDTO.setContent(photo.getContent());
        String imageUrl = photo.getImageUrl();
        String[] split = imageUrl.split(",");
        userDetailDTO.setPhotoUrlList(Arrays.asList(split));
        userDetailDTO.setCreatedTime(photo.getCreatedTime());
        return userDetailDTO;
    }

    @Override
    public Integer updateAuditPhoto(Integer photoId, Integer auditorId) {
        return photoDao.updateAuditPhoto(photoId,auditorId);
    }

    @Override
    public Photo selectPhotoByPhotoIdAndNoAudit(Integer photoId) {
        return photoDao.selectPhotoByPhotoIdAndNoAudit(photoId);
    }

    @Override
    public PageInfo<PhotoDTO> selectAllPhotoByWebCondition(Integer pageNum, Integer pageSize, String title, String content, Integer userId) {
        Page<PhotoDTO> page=new Page<>(pageNum,pageSize);
        Integer skip= (pageNum-1)*pageSize;
        //根据UserId查询该userId在哪个组织下
        //信息不互通，党支部，总支
        //根据userId去查询OrganizationId
        Organization organization = userOrganizationService.getOrganizationByUserId(userId);
        //判断当前组织层级是哪一个层级
        Integer grandParentId = organizationDao.getOrganizationByOrganizationId(organization.getParentId()).getParentId();
        //创建photoList List<Photo> photoList
        List<PhotoDTO> photoList = new ArrayList<>();
        List<Integer> organizationIdList = new ArrayList<>();
        if (grandParentId == 0){
            //说明该层级是党总支部,获取总支和下面支部的所有随手拍照片
            organizationIdList.addAll(organizationDao.getOrganizationIdListByParentId(organization.getId()));
        }
        //else是本组织的
        organizationIdList.add(organization.getId());
        photoList = photoDao.selectAllPhoto(content,title,organizationIdList);
        List<PhotoDTO> photoUserDTOList=new ArrayList<>();
        if(photoList.size()==0){
            page.addAll(photoUserDTOList);
            PageInfo<PhotoDTO> pageInfo=new PageInfo<>(page);
            return pageInfo;
        }
        List<Integer> userIdList = photoList.stream().map(PhotoDTO::getAuditorId).collect(Collectors.toList());
        List<User> auditorList = userDao.getUserListByIds(userIdList);
        Map<Integer, String> userNameMap = auditorList.stream().collect(Collectors.toMap(User::getId, User::getName));

        photoList.stream().map(photo ->{
            String[] split = photo.getImageUrl().split(",");
            photo.setPhotoUrlList(Arrays.asList(split));
            photo.setAuditorName(userNameMap.get(photo.getAuditorId()));
            return photo;
        }).collect(Collectors.toList());

        page.setTotal(photoList.size());
        photoUserDTOList = photoList.stream().skip(skip)
                .limit(pageSize).collect(Collectors.toList());

        page.addAll(photoUserDTOList);
        return new PageInfo<>(page);
    }

}
